// **************************************************************
// Com ++ Framework by the C++ World
// Please report defects: mailto:compp@cplusplusworld.com
// Please visit: http://www.cplusplusworld.com/socketlibrary.html
// **************************************************************

#include <iostream>
#include <errno.h>
#include <pthread.h>

#include "SysPlusPlus/syscall.h"
#include "ComPlusPlus/Mutex.h"


/** Constructor
 * Creates a mutex with standard setting
*/
compp::Mutex::Mutex(){

  //MutexId = NULL ;
  

  if ( 0 == syspp::Call::Pthread_mutex_init( &MutexId, NULL ) ) {

  }

}

/** Destructor
 * Entirely deletes the Mutex from the system
*/
compp::Mutex::~Mutex(){

  syspp::Call::Pthread_mutex_destroy( &MutexId );

}

/** Locks a semaphore
 * The method blocks until the semaphore can be locked
*/
bool compp::Mutex::Lock(){

  if ( 0 != syspp::Call::Pthread_mutex_lock ( &MutexId ) ) {
    return false;
  }
  
  return true;
}

/** Trylocks a semaphore
 * The method tries to lock the seamphore.
 * It it is already locked, the method returns false
 * It the Mutlex can be locked, it is locked and true is returned 
 * */ 
bool compp::Mutex::TryLock(){

  if ( 0 != syspp::Call::Pthread_mutex_trylock ( &MutexId ) ) {
    return false;
  }
  
  return true;
}

/** Unlocks the seamphore
 */
bool compp::Mutex::UnLock(){


  if ( 0 != syspp::Call::Pthread_mutex_unlock ( &MutexId ) ) {
    return false;
  }
  
  return true;

}


compp::CriticalSection::CriticalSection ( compp::Mutex & M ) {
  mMutex = &M;
  mMutex->Lock();
}

compp::CriticalSection::~CriticalSection (  ) {
  mMutex->UnLock();
}

#ifdef SPECIALDEBUG


static compp:Mutex sMutex;


void foo () {
  compp::CriticalSection cs ( sMutex );

  std::cout << "----------- 5 -----------\n";


}

int main ( int argc, char *argv [] ) {
  gen::GMutex *g = new gen::GMutex ();

  for ( int i = 1 ; i < 100; ++ i ) {

    if ( ! g->Lock())
      std::cout << "Error Lock\n" ;

    if ( ! g->UnLock())
      std::cout << "Error UnLock\n" ;

  } 

  return 0;
}

#endif


